package main

import (
	"fmt"
	"net/http"
	"net/url"
	"os"
)

func main() {
	fmt.Println(os.PathSeparator)
	//注册回调函数
	http.HandleFunc("/", myHandler)
	//绑定监听地址
	http.ListenAndServe("127.0.0.1:8000", nil)
}

func myHandler(w http.ResponseWriter, r *http.Request) {
	//fmt.Println(r.URL)
	OpenAndSendFile(r.URL.String(), w)
}

func OpenAndSendFile(fileName string, w http.ResponseWriter) {
	if fileName == "/favicon.ico" {
		return
	}

	cwdPath, _ := os.Getwd()
	fileName, err := url.QueryUnescape(fileName)
	filePath := cwdPath + "/go_learn" + fileName

	fp, err := os.Open(filePath)
	if err != nil {
		fmt.Println("open error", err)
		w.Write([]byte("no such file"))
		return
	}
	defer fp.Close()

	buf := make([]byte, 4096)
	for {
		n, _ := fp.Read(buf)
		if n == 0 {
			return
		}
		w.Write(buf[:n])
	}
}
